#include "networkprocessing.h"
#include <QtWidgets>
#include <QtNetwork>
#include <QDebug>
#include <QMessageBox>
#include "widget.h"
NetworkProcessing::NetworkProcessing()
    :s_Information(Information::get())
{
    connect(&m_tcpServer,SIGNAL(newConnection()),this,SLOT(acceptConnection()));
}
void NetworkProcessing::start(){
    qDebug() << "start listening...";
    if(!m_tcpServer.listen(QHostAddress::Any, 45454)){
        qDebug()<<m_tcpServer.errorString();
        close();
        return;
    }
}
void NetworkProcessing::acceptConnection(){
    m_tcpServerConnection=m_tcpServer.nextPendingConnection();
    QString ipAddr = m_tcpServerConnection->peerAddress().toString();
    qDebug()<<"有新的连接"<<ipAddr;
    s_Information.networkStatic = true;
    connect(m_tcpServerConnection,SIGNAL(readyRead()),this,SLOT(updateServerProgress()));
    connect(m_tcpServerConnection,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError)));
    //关闭服务器不再监听，直接进入数据收发
    // 发送连接建立的信号
    sendServerTcpConnectStatic(true);
    m_tcpServer.close();
}
void NetworkProcessing::updateServerProgress(){
    qDebug()<<"开始接收数据";
    QByteArray arry = m_tcpServerConnection->readAll();
    QJsonDocument jsonDocument = QJsonDocument::fromJson(arry);
    QJsonObject jsonObject = jsonDocument.object();
    qDebug()<<arry;
    // TODO 这里做简单的判断，后期可以加工
    // 根据数据类型来分配给不同处理函数
    int heartBeat = jsonObject.value("HeartBeat").toInt();
    if(heartBeat == 1)
    {
        return;
    }
    int dataType = jsonObject.value("datatype").toInt();
    qDebug()<<"DataType"<<dataType;
    switch (dataType) {
    case 1:
    case 2:
    case 5:
        s_Information.processDataPackage(jsonObject);
        break;
    case 3:
    case 4:
        s_Information.processFilePackage(jsonObject);
        break;
    case 6:
    case 7:
        s_Information.processTelecontrolPackage(jsonObject);
        break;
    default:
        qDebug()<<"未支持的数据类型";
        break;
    }
    // TODO 数据处理结束，发送信号给显示端
    sendClientStatic();
}

void NetworkProcessing::displayError(QAbstractSocket::SocketError socketError){
    Q_UNUSED(socketError)
    qDebug()<<m_tcpServerConnection->errorString();
    m_tcpServerConnection->close();
    sendServerTcpConnectStatic(false);
    start();

}
void NetworkProcessing::sendServerTcpConnectStatic(bool flag)
{
    emit serverTcpConnectStatic(flag);
}
void NetworkProcessing::sendClientStatic()
{
    emit ClientStatic();
}
void NetworkProcessing::send(QJsonObject sendJson)
{
    // start to sending
    qDebug()<<"开始发送数据";
    qDebug()<<sendJson;
    QJsonDocument jsonDocument;
    jsonDocument.setObject(sendJson);
    QByteArray dataArray = jsonDocument.toJson();
    m_tcpServerConnection->write(dataArray,dataArray.length());
}
